//
//  NSCalendar+YWDateConvertor.m
//  YWCalendar
//
//  Created by YR on 2017/5/26.
//  Copyright © 2017年 YR. All rights reserved.
//

#import "NSCalendar+YWDateConvertor.h"

static const NSTimeInterval kTimeIntervalOneDay = 3600 * 24;

@implementation NSCalendar (YWDateConvertor)
// 给定一时刻，返回该时刻对应当天的开始时时刻
- (NSDate*)yw_dayStartDateForDate:(NSDate*)date {
    NSDateComponents* components = [self yw_yearMonthDayFromDate:date];
    return [self yw_dateFromYearMonthDay:components];
}

// 给定一时刻，返回对应的年月日
- (NSDateComponents*)yw_yearMonthDayFromDate:(NSDate*)date {
    return [self components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay
                   fromDate:date];
}

// 给定一年月日，返回对应的时刻
- (NSDate*)yw_dateFromYearMonthDay:(NSDateComponents*)components {
    // 注意此处不使用components.date的原因是因为components.date需要设置components的calendar
    // see http://stackoverflow.com/a/22112581/792416
    return [self dateFromComponents:components];
}

- (NSDate*)yw_dateFromYear:(NSUInteger)year
                     month:(NSUInteger)month
                       day:(NSUInteger)day {
    NSDateComponents* components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    components.day = day;
    return [self yw_dateFromYearMonthDay:components];
}

// 给定一年月日，返回第未来的N天, N为负值是表示过去的第N天
- (NSDateComponents*)yw_dayFromDay:(NSDateComponents*)day
                     withDayOffset:(NSInteger)dayOffset {
    NSDate* date = [self yw_dateFromYearMonthDay:day];
    date = [self yw_dateFromDate:date withDayOffset:dayOffset];
    return [self yw_yearMonthDayFromDate:date];
}

// 给定一时刻，返回N天之后的时刻，N为复制表示已经过去的N天之前的时刻，返回值不一定为当天的开始时间
- (NSDate*)yw_dateFromDate:(NSDate*)date
             withDayOffset:(NSInteger)dayOffset {
    return [NSDate dateWithTimeInterval:dayOffset * kTimeIntervalOneDay
                              sinceDate:date];
}

// 给定两时刻，计算他们之间所差的天数 [toDate - fromDate] / 24 * 3600
- (NSInteger)yw_dayIntervalFromDate:(NSDate*)fromDate
                             toDate:(NSDate*)toDate {
    return (NSInteger)([toDate timeIntervalSinceDate:fromDate] / kTimeIntervalOneDay);
}


@end
